<template>
  <view class="fault-report-container">
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">故障报修</text>
    </view>

    <scroll-view class="form-container" scroll-y>
      <!-- 设备信息 -->
      <view class="form-card">
        <view class="form-section">
          <!-- 设备类型 -->
          <view class="form-item required">
            <text class="form-label">设备类型</text>
            <view class="radio-group">
              <label 
                class="radio-item" 
                v-for="item in deviceTypeOptions" 
                :key="item.value"
              >
                <radio 
                  :value="item.value" 
                  :checked="formData.deviceType === item.value"
                  @click="formData.deviceType = item.value"
                  color="#007AFF"
                />
                <text class="radio-text">{{item.label}}</text>
              </label>
            </view>
          </view>

          <!-- 设备编码 -->
          <view class="form-item required">
            <text class="form-label">设备编码</text>
            <view class="input-with-action">
              <input 
                class="form-input" 
                placeholder="输入二维码编号" 
                v-model="formData.cabinetSn"
                maxlength="50"
              />
              <button class="action-btn" @click="handleScan">扫一扫</button>
            </view>
          </view>

          <!-- 故障类型 -->
          <view class="form-item required">
            <text class="form-label">故障类型</text>
            <picker 
              class="form-picker" 
              mode="selector" 
              :range="faultTypeOptions"
              @change="onFaultTypeChange"
            >
              <view class="picker-content">
                <text class="picker-text" :class="{placeholder: !formData.alarmType}">
                  {{formData.alarmType || '选择故障类型'}}
                </text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>

          <!-- 故障描述 -->
          <view class="form-item required">
            <text class="form-label">故障描述</text>
            <textarea 
              class="form-textarea" 
              placeholder="输入故障描述" 
              v-model="formData.alarmDesc"
              maxlength="500"
              :auto-height="true"
            />
            <view class="textarea-counter">
              <text class="counter-text">{{formData.alarmDesc.length}}/500</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 图片上传 -->
      <view class="form-card">
        <view class="form-section">
          <view class="form-item required">
            <text class="form-label">图片</text>
            <view class="upload-section">
              <view class="upload-tips">
                <text class="tip-text">请上传故障相关图片（最多6张）</text>
              </view>
              <view class="image-list">
                <view 
                  class="image-item" 
                  v-for="(image, index) in imageList" 
                  :key="index"
                >
                  <image :src="image" class="image-preview" mode="aspectFill"></image>
                  <view class="image-remove" @click="removeImage(index)">
                    <text class="remove-icon">×</text>
                  </view>
                </view>
                <view 
                  class="upload-box" 
                  v-if="imageList.length < 6"
                  @click="uploadImage"
                >
                  <view class="upload-icon">
                    <text class="icon">📷</text>
                  </view>
                  <text class="upload-text">上传图片</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部提交按钮 -->
    <view class="action-bar">
      <button class="submit-btn" @click="handleSubmit">提交</button>
    </view>
  </view>
</template>

<script>
import api from '@/config/api.js'

export default {
  data() {
    return {
      formData: {
        deviceType: 'cabinet',
        cabinetSn: '',
        alarmPhoto: '',
		alarmPhotoName:'',
		alarmType:'',
        alarmDesc: ''
      },
      imageList: [],
      deviceTypeOptions: [
        { value: 'cabinet', label: '电柜' },
        { value: 'battery', label: '电池' },
        { value: 'other', label: '其他设备' }
      ],
      faultTypeOptions: [
        '硬件故障',
        '软件故障',
        '网络故障',
        '电源故障',
        '门锁故障',
        '电池故障',
        '其他故障'
      ]
    }
  },

  methods: {
    handleScan() {
      uni.scanCode({
        onlyFromCamera: true,
        scanType: ['qrCode'],
        success: (res) => {
          console.log('扫码结果:', res)
          this.formData.deviceCode = res.result
          uni.showToast({
            title: '扫码成功',
            icon: 'success'
          })
        },
        fail: (err) => {
          console.error('扫码失败:', err)
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },

    onFaultTypeChange(e) {
      const index = e.detail.value
      this.formData.alarmType = this.faultTypeOptions[index]
    },

    uploadImage() {
      const count = 6 - this.imageList.length
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          const files = res.tempFiles
          
          // 检查文件大小
          for (let i = 0; i < files.length; i++) {
            if (files[i].size > 2 * 1024 * 1024) {
              uni.showToast({
                title: `第${i + 1}张图片超过2M`,
                icon: 'none'
              })
              return
            }

            // 检查文件类型
            const fileType = files[i].name.split('.').pop().toLowerCase()
            if (!['jpg', 'jpeg', 'png'].includes(fileType)) {
              uni.showToast({
                title: `第${i + 1}张图片格式不支持`,
                icon: 'none'
              })
              return
            }
          }

          // 添加到图片列表
          this.imageList = [...this.imageList, ...tempFilePaths]

          
          api.fix.uploadFile({file:files[0]},tempFilePaths[0]).then((upload)=>{
          	uni.showToast({
          		title: '图片已上传',
          		icon: 'success'
          	})
          	console.log('upload',upload)
          	this.formData.alarmPhoto = upload.url
          	this.formData.alarmPhotoName = upload.name || '电柜图片'
          })
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
        }
      })
    },

    removeImage(index) {
      this.imageList.splice(index, 1)
    },

    validateForm() {
      if (!this.formData.cabinetSn) {
        uni.showToast({ title: '请输入设备编码', icon: 'none' })
        return false
      }
      if (!this.formData.alarmType) {
        uni.showToast({ title: '请选择故障类型', icon: 'none' })
        return false
      }
      if (!this.formData.alarmDesc) {
        uni.showToast({ title: '请输入故障描述', icon: 'none' })
        return false
      }
      if (this.imageList.length === 0) {
        uni.showToast({ title: '请上传至少一张图片', icon: 'none' })
        return false
      }
      return true
    },

    async handleSubmit() {
      if (!this.validateForm()) {
        return
      }

      try {
        uni.showLoading({
          title: '提交中...',
          mask: true
        })

        // 构建提交数据
        const submitData = {
          deviceType: this.formData.deviceType,
          cabinetSn: this.formData.cabinetSn,
          alarmType: this.formData.alarmType,
          alarmDesc: this.formData.alarmDesc,
          alarmPhoto: this.formData.alarmPhoto // 实际开发中需要先上传图片到服务器
        }

        const result = await api.fix.addDevicealarm(submitData)
        
        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })

        // 清空表单
        this.resetForm()

        // 跳转到故障列表页
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/fix/fix'
          })
        }, 1500)

      } catch (error) {
        console.error('提交故障报修失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    resetForm() {
      this.formData = {
        deviceType: 'cabinet',
        cabinetSn: '',
        alarmType: '',
        alarmDesc: '',
		alarmPhoto:''
      }
      this.imageList = []
    }
  }
}
</script>

<style scoped>
.fault-report-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 页面标题 */
.page-header {
  background-color: #fff;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

/* 表单容器 */
.form-container {
  height: calc(100vh - 200rpx);
  padding: 20rpx;
  box-sizing: border-box;
}

.form-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
}

.form-section {
  padding: 30rpx;
}

/* 表单项 */
.form-item {
  margin-bottom: 40rpx;
}

.form-item.required .form-label::before {
  content: '*';
  color: #f5222d;
  margin-right: 8rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
}

/* 单选组 */
.radio-group {
  display: flex;
  gap: 40rpx;
  flex-wrap: wrap;
}

.radio-item {
  display: flex;
  align-items: center;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

/* 输入框 */
.form-input {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #e8e8e8;
}

/* 输入框带操作按钮 */
.input-with-action {
  display: flex;
  gap: 20rpx;
}

.input-with-action .form-input {
  flex: 1;
}

.input-with-action .action-btn {
  width: 200rpx;
  height: 80rpx;
  background-color: #f5f5f5;
  color: #1890ff;
  border: 1rpx solid #1890ff;
  border-radius: 8rpx;
  font-size: 24rpx;
  line-height: 80rpx;
  white-space: nowrap;
}

/* 选择器 */
.form-picker {
  width: 100%;
}

.picker-content {
  width: 100%;
  height: 80rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1rpx solid #e8e8e8;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.picker-text.placeholder {
  color: #999;
}

.picker-arrow {
  font-size: 24rpx;
  color: #999;
}

/* 文本域 */
.form-textarea {
  width: 100%;
  min-height: 160rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1rpx solid #e8e8e8;
  line-height: 1.4;
}

.textarea-counter {
  text-align: right;
  margin-top: 8rpx;
}

.counter-text {
  font-size: 24rpx;
  color: #999;
}

/* 上传区域 */
.upload-section {
  border: 1rpx solid #e8e8e8;
  border-radius: 8rpx;
  overflow: hidden;
}

.upload-tips {
  padding: 16rpx 20rpx;
  background-color: #fafafa;
  border-bottom: 1rpx solid #f0f0f0;
}

.tip-text {
  font-size: 24rpx;
  color: #999;
}

.image-list {
  padding: 20rpx;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
}

.image-preview {
  width: 100%;
  height: 100%;
}

.image-remove {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-icon {
  color: white;
  font-size: 30rpx;
  font-weight: bold;
}

.upload-box {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #e8e8e8;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.upload-icon {
  font-size: 48rpx;
  margin-bottom: 12rpx;
  color: #999;
}

.upload-text {
  font-size: 24rpx;
  color: #999;
}

/* 底部提交按钮 */
.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.06);
}

.submit-btn {
  background-color: #1890ff;
  color: #fff;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  line-height: 80rpx;
}
</style>